﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Threading.Tasks;
using Hangfire;
using RafikiSIS_Site.Models;
using RafikiSIS_Site.Libraries;

namespace RafikiSIS_Site.Controllers
{

    [Authorize]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            if (Request.IsAuthenticated)
            {
                if (Session["AuthUserFullName"] == null)
                {
                    Session["AuthUserFullName"] = BasicFuncs.GetNameFromUsername(User.Identity.Name);
                    Session["AuthUserPersonID"] = BasicFuncs.GetPersonIDFromUsername(User.Identity.Name);
                }
            }
            return View();
        }

        public ActionResult Search()
        {
            int UserID = User.Identity.GetEntityID();
            DataTable SchoolView = DataFuncs.GetAnyTable("(SELECT * FROM EntityRelationships JOIN Entities ON EntityRelationships.Entity2ID=Entities.EntityID) x ", "Entity1ID=" + UserID.ToString() + " AND EntityType='SchoolDIV'", "");
            if (SchoolView.Rows.Count > 0)
            {
                @ViewBag.SchoolDIVID = SchoolView.Rows[0]["Entity2ID"].ToString();
                return PartialView();
            }
            else return Content("<p>You do not have a direct relationship to a school.</p>");
            
        }


        // New Main Code:
        public ActionResult ShowEntity(string EntityID, string ChainSoFar = "", string EntityType = "", string EntitySubType = "", string CallingFunction = "")
        {
            // First Clean Up Entity and Chain info sent...
            if (ChainSoFar == "")
            {
                ViewBag.ChainSoFar = ";";
            }
            else
            {
                ViewBag.ChainSoFar = ChainSoFar;
            }
            if (EntityType == "" || EntityType == null)
            {
                ViewBag.EntityType = "Person";
                ViewBag.EntitySubType = "";
                ViewBag.EntityTypeSubType = "Person";
            }
            else
            {
                ViewBag.EntityType = EntityType;
                ViewBag.EntitySubType = EntitySubType;
                if (EntitySubType == "" || EntitySubType == null || EntitySubType == "null" || EntitySubType == "Null")
                {
                    ViewBag.EntityTypeSubType = EntityType;
                    EntitySubType = "";
                }
                else
                {
                    ViewBag.EntityTypeSubType = EntityType + "." + EntitySubType;
                }
            }

            // Next Determine if a FunctionCalled This, in which case we want to look for possible Template information
            string TemplateCode = "";
            if (CallingFunction != "")
            {
                DataTable FunctionView = DataFuncs.GetAnyTable("DefinedRelationshipFunctions", "ShortFunctionName='" + CallingFunction + "'", "");
                if (FunctionView.Rows.Count > 0)
                {
                    string TemplateName = FunctionView.Rows[0]["TemplateGroupName"].ToString();
                    if (TemplateName != "")
                    {
                        DataTable TemplateView = DataFuncs.GetAnyTable("DefinedEntityTemplates", "TemplateGroupName='" + TemplateName + "' AND EntityType+COALESCE('.'+EntitySubType,'') = '" + EntityType + "'", "");
                        if (TemplateView.Rows.Count > 0)
                        {
                            TemplateCode = TemplateView.Rows[0]["TemplateCode"].ToString();
                            if (TemplateCode.Substring(0, 1) == "*")
                            {
                                switch (TemplateCode.Substring(0, 9))
                                {
                                    case "*URLLoad(":
                                        return URLLoad(EntityID, TemplateCode.Remove(TemplateCode.Length - 1).Substring(9));
                                        break;
                                    case "*HTMLLoad":
                                        return HTMLLoad(EntityID, TemplateCode.Remove(TemplateCode.Length - 1).Substring(10));
                                        break;
                                }
                            }
                        }
                    }
                }
            }
            ViewBag.EntityID = EntityID;
            // The following two lines set a unique VM for every page or partial page using a simple incrementing function
            Session["VMCounter"] = BasicFuncs.IncrementSessionCounter(Session["VMCounter"]);
            ViewBag.VMName = "VM" + Session["VMCounter"];
            


            // The following gets the list of attributes for the particular Entity and passes them as a list/array
            ViewBag.AttList = new List<ViewEntityAttributes>();
            Dictionary<string, string> myentity = new Dictionary<string, string>();
            myentity.Add("RequestorEntityID", "0");
            myentity.Add("RequestedChain", ViewBag.EntityTypeSubType);
            myentity.Add("CommandType", "Attributes");
            DataTable Attributes = DataFuncs.GetSQLsp("ReadDataFromDB_New", myentity);
            foreach (DataRow row in Attributes.Rows)
            {
                ViewBag.AttList.Add(new ViewEntityAttributes() { AttributeName = row["AttributeName"].ToString(), AttributeType = row["DataType"].ToString() });
            }

            return PartialView();
        }


        public ActionResult ShowEntityFull(string EntityID, string ChainSoFar = "", string EntityType = "", string EntitySubType = "")
        {
            ViewBag.EntityID = EntityID;
            // The following two lines set a unique VM for every page or partial page using a simple incrementing function
            Session["VMCounter"] = BasicFuncs.IncrementSessionCounter(Session["VMCounter"]);
            ViewBag.VMName = "VM" + Session["VMCounter"];
            
            if (ChainSoFar == "")
            {
                ViewBag.ChainSoFar = ";";
            }
            else
            {
                ViewBag.ChainSoFar = ChainSoFar;
            }
            if (EntityType == "" || EntityType == null)
            {
                ViewBag.EntityType = "Person";
                ViewBag.EntitySubType = "";
                ViewBag.EntityTypeSubType = "Person";
            }
            else
            {
                ViewBag.EntityType = EntityType;
                ViewBag.EntitySubType = EntitySubType;
                if (EntitySubType == "" || EntitySubType == null || EntitySubType == "null" || EntitySubType == "Null")
                {
                    ViewBag.EntityTypeSubType = EntityType;
                    EntitySubType = "";
                }
                else
                {
                    ViewBag.EntityTypeSubType = EntityType + "." + EntitySubType;
                }
            }

            // The following gets the list of attributes for the particular Entity and passes them as a list/array
            ViewBag.AttList = new List<ViewEntityAttributes>();
            Dictionary<string, string> myentity = new Dictionary<string, string>();
            myentity.Add("RequestorEntityID", "10214");
            myentity.Add("RequestedChain", ViewBag.EntityTypeSubType);
            myentity.Add("CommandType", "Attributes");
            DataTable Attributes = DataFuncs.GetSQLsp("ReadDataFromDB_New", myentity);
            foreach (DataRow row in Attributes.Rows)
            {
                ViewBag.AttList.Add(new ViewEntityAttributes() { AttributeName = row["AttributeName"].ToString(), AttributeType = row["DataType"].ToString(), Groupable = bool.Parse(row["Groupable"].ToString()) });
            }

            return View("ShowEntity");
        }

        public ActionResult ShowView(string FunctionName, string Chainsofar, string TD = "", string JsonParameters = "")
        {
            ViewBag.FunctionName = FunctionName;
            ViewBag.Chainsofar = Chainsofar;
            // The following two lines set a unique VM for every page or partial page using a simple incrementing function
            Session["VMCounter"] = BasicFuncs.IncrementSessionCounter(Session["VMCounter"]);
            ViewBag.VMName = "VM" + Session["VMCounter"];
            
            ViewBag.JsonParameters = JsonParameters;
            ViewBag.TD = TD;
            // The following gets the list of attributes for the particular Function View and passes them as a list/array
            ViewBag.AttList = new List<ViewEntityAttributes>();
            Dictionary<string, string> myentity = new Dictionary<string, string>();
            myentity.Add("RequestorEntityID", "0");
            myentity.Add("RequestedChain", ViewBag.FunctionName);
            myentity.Add("CommandType", "FunctionAttributes");
            DataTable Attributes = DataFuncs.GetSQLsp("ReadDataFromDB_New", myentity);
            ViewBag.NumberofAttributes = 0;
            foreach (DataRow row in Attributes.Rows)
            {
                ViewBag.AttList.Add(new ViewEntityAttributes() { AttributeName = row["AttributeName"].ToString(), AttributeType = row["DataType"].ToString(), Groupable = bool.Parse(row["Groupable"].ToString()) });
                ViewBag.NumberofAttributes++;
            }
            
            return PartialView();
        }

        public ActionResult ShowViewFull(string FunctionName, string Chainsofar, string TD = "CURRENT.Term", string JsonParameters = "")
        {
            ViewBag.FunctionName = FunctionName;
            ViewBag.Chainsofar = Chainsofar;
            // The following two lines set a unique VM for every page or partial page using a simple incrementing function
            Session["VMCounter"] = BasicFuncs.IncrementSessionCounter(Session["VMCounter"]);
            ViewBag.VMName = "VM" + Session["VMCounter"];
            
            ViewBag.JsonParameters = JsonParameters;
            ViewBag.TD = TD;
            // The following gets the list of attributes for the particular Function View and passes them as a list/array
            ViewBag.AttList = new List<ViewEntityAttributes>();
            Dictionary<string, string> myentity = new Dictionary<string, string>();
            myentity.Add("RequestorEntityID", "0");
            myentity.Add("RequestedChain", ViewBag.FunctionName);
            myentity.Add("CommandType", "FunctionAttributes");
            DataTable Attributes = DataFuncs.GetSQLsp("ReadDataFromDB_New", myentity);
            ViewBag.NumberofAttributes = 0;
            foreach (DataRow row in Attributes.Rows)
            {
                ViewBag.AttList.Add(new ViewEntityAttributes() { AttributeName = row["AttributeName"].ToString(), AttributeType = row["DataType"].ToString(), Groupable = bool.Parse(row["Groupable"].ToString()) });
                ViewBag.NumberofAttributes++;
            }

            return View("ShowView");
        }

        public ActionResult ShowURL(string EntityID)
        {
            DataTable EntityView = DataFuncs.GetAnyTable("Attributes", "EntityID=" + EntityID+" AND AttributeID=1064", "");
               return new RedirectResult(EntityView.Rows[0]["AttributeValueString"].ToString());
        }

        public ActionResult URLLoad(string EntityID, string LinkName)
        {
            string EntityType = DataFuncs.ReadDataColumn("Entities", "EntityID='" + EntityID + "'", "EntityType");
            string AttID = DataFuncs.ReadDataColumn("DefinedAttributes","AttributeName='"+LinkName+"' AND EntityType='"+EntityType+"'","AttributeID");
            DataTable EntityView = DataFuncs.GetAnyTable("Attributes", "EntityID=" + EntityID + " AND AttributeID=" + AttID, "");
            if (EntityView.Rows.Count>0)
            {
                return new RedirectResult(EntityView.Rows[0]["AttributeValueString"].ToString());
            }
            else return Content("<p>No Data</p>");
        }

        public ActionResult HTMLLoad(string EntityID, string HTMLName)
        {
            string EntityType = DataFuncs.ReadDataColumn("Entities", "EntityID='" + EntityID + "'", "EntityType");
            string AttID = DataFuncs.ReadDataColumn("DefinedAttributes", "AttributeName='" + HTMLName + "' AND EntityType='" + EntityType + "'", "AttributeID");
            DataTable EntityView = DataFuncs.GetAnyTable("Attributes", "EntityID=" + EntityID + " AND AttributeID=" + AttID, "");
            if (EntityView.Rows.Count > 0)
            {
                return Content(EntityView.Rows[0]["AttributeValueString"].ToString());
            }
            else return Content("<p>No Data</p>");
        }


        [Authorize(Users="tchase,jstocksdale")]
        public ActionResult ProgReports()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Users = "tchase,jstocksdale")]
        public ActionResult ProgReports(string commandctrl)
        {
            switch(commandctrl)
            {
                case "fullprog":

                    break;
                default: 
                    break;
            }
            return View();
        }

        public ActionResult Resources()
        {
            
            
            return PartialView();
        }

        public ActionResult Exp(int EntityID = 0)
        {
            ViewBag.EntityID = EntityID;
            return PartialView();
        }

        public ActionResult Portraits()
        {
            return PartialView();
        }

        public ActionResult Survey()
        {
            return PartialView();
        }

        public ActionResult StudentSurvey()
        {
            return PartialView();
        }

        public ActionResult RecycleApp()
        {
            foreach (System.Collections.DictionaryEntry entry in HttpContext.Cache)
            {
                HttpContext.Cache.Remove((string)entry.Key);
            }
            ViewBag.Result = "Cache Cleared!";
            return View();
        }

        [Authorize(Users="tchase,jstocksdale")]
        public ActionResult EmailTasks()
        {
            ViewBag.HangfireStatus = "";
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        [Authorize(Users = "tchase,jstocksdale")]
        public ActionResult EmailTasks(string commandctrl, string bodytext="")
        {
            DataTable ParentEmails, StaffCourses, StaffEmail;
            string Subject;
            string MessageBody;
            Dictionary<string, string> myentry = new Dictionary<string, string>();

            switch(commandctrl)
            {
                case "StaffSurvey":

                    StaffCourses = DataFuncs.GetSQLsp("SP_SurveyDataCompletedCourses", myentry);
                    StaffCourses.Columns["TEACHERID"].ColumnName = "EntityID";

                    StaffEmail = new DataView(StaffCourses.Select("isdone='NOT DONE'").CopyToDataTable()).ToTable(true, "EntityID");
                    StaffEmail.Columns.Add("msg");

                    foreach(DataRow row in StaffEmail.Rows)
                    {
                        row["msg"] = "<p>Dear Teacher/Dorm Parent:</p><p>We still show that you have some surveys not completed  (Note: Bible/PE can ignore this automatic message if you have done half of your class as instructed.):</p>"
                      + BasicFuncs.HTMLListTemplate("<p>#COURSEID#: #NUMSTUDENTS# student surveys are #isdone#.</p>", StaffCourses.Select("EntityID="+row["EntityID"]).CopyToDataTable())
                      + "<p>If you think you entered data and you still received this message, please let me know right away. Or be sure to close and re-open your browser and try again.</p>"
                      + "<p>If you just have forgotten or been too busy or just missed a student or two, please log into PORTAL.RVA.ORG and select the SURVEY tab. We'll be running data analysis first thing tomorrow morning, so please help us by finishing this evening.</p>"
                        + "<p>Thanks,</p>"
                      + "<p>Jon Stocksdale</p>"
                      ;
                    }

                    BasicFuncs.SendEmail("Staff Surveys", "#msg#", StaffEmail,"jstocksdale@rva.org");
                   
                    break;
            case "SeniorParents2":
                    ParentEmails = DataFuncs.GetAnyTableCoreData("CURRENT_PARENTS", "[Student.GradYear]=2016");
                    ParentEmails.Columns["PersonID"].ColumnName = "EntityID";
                    Subject = "Important Graduation Information";
                    MessageBody=bodytext;
                        ViewBag.ResultMessage = BasicFuncs.SendEmail(Subject, MessageBody, ParentEmails,"deanwomen@rva.org",false);
                    break;


                   

                case "SeniorParents":
                    ParentEmails = DataFuncs.GetAnyTableCoreData("CURRENT_PARENTS", "[Student.GradYear]=2016");
                    ParentEmails.Columns["PersonID"].ColumnName = "EntityID";
                    Subject = "Important Graduation Information";
                    MessageBody = 
                        "<p>Hi senior parents</p>" +
                        "<p>The seniors are all off enjoying their senior safo and graduation just over a week away!</p>" +
                        "<p>I am working on finalizing details for graduation.</p>" +
                        "<p>Below is some important information:</p>" +
                        "<p>Housing: If you are staying on campus Wednesday night, you will receive an email from me early next week with information about where you will be staying. Please do not arrive at the dorm before 12pm on Wednesday. The boarding students are still moving out of the dorms on Wednesday morning and we need to wait until they are out of the dorm before graduation guest move in.&nbsp;</p>" +
                        "<p><strong>Meals</strong>: If you prepaid for your meals, just tell the person working the desk at the cafo that you have prepaid and they will check your name off of the list. You do not need to scan your students ID card &ndash; this will charge your account again for the meal. If you need to pay for your meals, please do so in the business office. Thursday lunch (after graduation) is provided by the school for all who attend the ceremony.</p>" +
                        "<p><strong>Transportation</strong>: For those who signed up for transportation, the buses to Mayfield and the Airport will leave at 3pm from Centennial parking lot. Please be early to pack the buses with luggage. If you have questions about transportation, please let me know.</p>" +
                        "<p><strong>Security</strong>: We have a new security company working with us and have implemented some new security procedures. In order to make your arrival to campus smooth, please read this. Please also make sure you arrive early enough to go through our security check at the gate.</p>" +
                        "<p><strong>When you arrive:</strong> At the gate, you will be asked to check in. Please tell the guards the name of the graduate that you are associated with. The guards will check your name off of the master list which includes the names that you gave me of people attending graduation. The guards will also spot check the IDs of adults in the car.&nbsp; If you are staying off campus and plan to be on campus the days before the graduation ceremony on Thursday, the guards will issue a visitor badge for the time you are on campus. <strong>Please pass this information on to the other guests who have been invited to this event</strong>.</p>" +
                        "<p>**To help this process go smoother, if you know people are coming for graduation and they are not on the list that you gave me, please email me their names. If they are not on the list, it will delay their admittance onto campus.</p>" +
                        "<p><strong>Parking</strong>: Please do NOT park around Centennial. On Graduation day this part of campus will be blocked off. Please park in one of the following areas: the Kedong parking lot (by the girls dorms and reserved for families with a girl graduating), the main Kiambogo parking lot, the grassy area above upper field or along the road.</p>" +
                        "<p><strong>On Graduation Day</strong>: Please enter through the Westervelt Gate. The AIC Gate will be closed. There will be sections of campus that will be closed off for most of the day to restrict flow of traffic and parking. After graduation, the AIC Gate will be open so you are welcome to exit this gate.</p>" +
                        "<p>If you have further questions, please let me know!</p>" +
                        "<p>We look forward to celebrating with you!</p>" +
                        "<p><strong>Emily Wiarda</strong></p>" +
                        "<p>Dean of Women</p>" +
                        "<p>Rift Valley Academy</p>";


                    //MessageBody = "<h2>TO: Parents of Class of 2016,</h2>" 
                    //    + "<p>Greetings from RVA! It's hard to believe we are halfway through senior year already! Below is some important information regarding graduation announcements, pictures, and housing for graduation. Please read carefully and respond where necessary.</p>"
                    //    + "<h2>Graduation Announcements</h2>"
                    //    + "<p>Attached you will find a picture of graduation announcements for this year. We are very happy to order these for you. The cost is 30 ksh per announcement (single fold announcement including envelope). We will place a single order for the class in March and they will be sent home with your child at the end of Term 2. If you would like to order announcements, please reply to this e-mail address with the number of announcements you would like. We will charge your RVA account. The deadline to order announcements is March 1.</p>"
                    //    + "<h2>Graduation Photos</h2>"
                    //    + "<p>Your child has already posed in their cap and gown, making graduation all that more real! We will not be ordering paper copies of photos for you, but instead will be making your child's photos available on portal.rva.org by the end of Term 2. From there, you will be free to download the photos and print them yourself. Look for an appropriate link on Portal at the end of term.</p>"
                    //    + "<h2>Graduation Arrangements</h2>"
                    //    + "<p>Graduation is on Thursday, July 14, 2016. We will be sending out more detailed information regarding graduation in Term 3, but for now we wanted to let you know that housing will be provided for you on campus on Wednesday, July 13. If you wish to stay in Kijabe before Wednesday or after graduation on Thursday, you will need to make your own arrangements with Kijabe or Moffatt Guesthouse. We hope this helps as you begin to make plans for July.</p>"
                    //    + "<p>Thank you for the privilege of walking through senior year with your child! We are looking forward to what the Lord has for us the rest of this year!</p>"
                    //    +"<h2>FROM: Your Class of 2016 Sponsors</h2>";
                        ViewBag.ResultMessage = BasicFuncs.SendEmail(Subject, MessageBody, ParentEmails,"deanwomen@rva.org",true);
                    break;
                case "PortraitNotify":
                    ParentEmails = DataFuncs.GetAnyTable("CURRENT_PARENTS");
                    ParentEmails.Columns["PersonID"].ColumnName = "EntityID";
                    Subject = "RVA Student Portrait Orders";
                    MessageBody = "<p>Dear Parents,</p>" 
                        +"<p>RVA is once again making portrait prints of your children available to you at cost.</p>"
                        +"<p>This year, though, we are automating the process a bit more, so you will place your "
                        +"order on the new RVA Portal: <a href='https://portal.rva.org'>portal.rva.org</a></p>"
                        +"<p>If you have not already logged into Portal, you need to find the email that we sent you "
                        +"with your username (it will be one of your email addresses) and a temporary password.</p>"
                        +"<p>Once you are logged on, you will see your students progress report (if you have children "
                        +"in grades 7 through 12), a list of RVA resources (calendars, menus, and other resources), "
                        +"and a tab marked PORTRAIT-ORDERS.</p>"
                        +"<p>Click on the PORTRAIT-ORDERS tab and you will see a picture for each of your children"
                        +"and a place to specify how many prints of each size you want for each of your children.</p>"
                        +"<p>Prints will be delivered in your end of term packet which will be sent home with your oldest "
                        +"child and your account will be charged.</p>"
                        +"<p>Here are the charges for prints in Kenya Shillings: (Sizes are in inches.)</p>"
                        +"<ul>"
                        +"<li>4x6:  25/=</li>"
                        +"<li>A set of 4 wallets (cut):  125/=</li>"
                        +"<li>5x7:  45/=</li>"
                        +"<li>8x10:  200/=</li>"
                        +"</ul>"
                        +"<p>Note: The photos which will be sent to the printer are being touched up for color correction and "
                        +"slight skin imperfections. The pictures that you see online may not have been fully edited yet.</p>"
                        +"<p><b>ORDERS MUST BE PLACED NO LATER THAN November 9th to be received this term.</b></p>";
                    BasicFuncs.SendEmail(Subject, MessageBody, ParentEmails);
                    break;
                case "HangfireAccountExpiration":
                    RecurringJob.AddOrUpdate(() => EmailFuncs.SendPasswordExpirationNotices(), Cron.Daily);
                    break;
                case "TestuserButton":
                    ADFuncs ADQuery = new ADFuncs();
                    ADQuery.GetUserPasswordExpiration("cstocksdale16");
                    break;
                default:
                    ViewBag.ResultMessage = "Invalid option selected";
                    break;
            }

            return View();
        }

        public ActionResult Email(string emailtask)
        {
           // // The following gets the list of attributes for the particular Entity and passes them as a list/array
           // ViewBag.MailList = new List<ViewEntityAttributes>();
           // Dictionary<string, string> emailentity = new Dictionary<string, string>();
           // emailentity.Add("RequestorEntityID", "10214");
           // emailentity.Add("CommandName", emailtask);
           // emailentity.Add("CommandType", "Email");
           // DataTable MailTask = DataFuncs.GetSQLsp("ReadDataFromDB", emailentity);
           //// MailTask.Rows(0).
           // foreach (DataRow row in Attributes.Rows)
           // {
           //     ViewBag.AttList.Add(new ViewEntityAttributes() { AttributeName = row["AttributeName"].ToString(), AttributeType = row["DataType"].ToString() });
           // }

            return View();

        }

        
    }
}